package com.zhangfb95.crosschain.server.controller;

import com.zhangfb95.crosschain.infra.model.Result;
import com.zhangfb95.crosschain.protocol.exc.request.GetAccountExcReq;
import com.zhangfb95.crosschain.protocol.exc.request.SendExcReq;
import com.zhangfb95.crosschain.protocol.exc.request.SignExcReq;
import com.zhangfb95.crosschain.protocol.exc.response.GetAccountExcRes;
import com.zhangfb95.crosschain.protocol.exc.response.SendExcRes;
import com.zhangfb95.crosschain.protocol.routerplugincontroller.request.GetAccountPluginReq;
import com.zhangfb95.crosschain.protocol.routerplugincontroller.request.SignPluginReq;
import com.zhangfb95.crosschain.protocol.routerplugincontroller.response.GetAccountPluginRes;
import com.zhangfb95.crosschain.protocol.routerplugincontroller.response.SignPluginRes;
import com.zhangfb95.crosschain.server.service.CrossChainService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author zhangfubing
 * @since 2023/11/3
 */
@RequestMapping("/plugin")
@RestController
public class PluginController {

    @Autowired
    private CrossChainService crossChainService;

    @PostMapping("/getAccount")
    public Result<GetAccountPluginRes> getAccount(@RequestBody @Validated GetAccountPluginReq req) {
        GetAccountExcReq protoReq = new GetAccountExcReq()
                .setUserId(req.getUserId())
                .setChainPath(req.getChainPath())
                .setPropertyKeys(req.getPropertyKeys());
        GetAccountExcRes protoRes = crossChainService.getAccount(req.getServerId(), protoReq);

        GetAccountPluginRes res = new GetAccountPluginRes()
                .setPublicKey(protoRes.getPublicKey())
                .setPropertyMap(protoRes.getPropertyMap());
        return Result.ok(res);
    }

    @PostMapping("/sign")
    public Result<SignPluginRes> sign(@RequestBody @Validated SignPluginReq req) {
        SignExcReq protoReq = new SignExcReq()
                .setUserId(req.getUserId())
                .setChainPath(req.getChainPath())
                .setBytes(req.getBytes());
        byte[] signedBytes = crossChainService.sign(req.getServerId(), protoReq).getSignedBytes();
        return Result.ok(new SignPluginRes().setSignedBytes(signedBytes));
    }

    @PostMapping("/send")
    public Result<SendExcRes> send(@RequestBody @Validated SendExcReq req) {
        return Result.ok(crossChainService.send(req));
    }
}
